#include	"LoginApp.h"
#include	"network/LoginService.h"
#include	"network/CenterConnector.h"
#include	<IniFile.h>

bool LoginApp::OnInit(Command & cmd) {
	IniFile conf;
	if (!conf.Load("./config.ini")) throw std::runtime_error("Load config.ini failed!!!");

	int log_level = conf.Get<int>("login", "log_level", ELog::Info);
	Logger::Instance().Init("login", "logs", 4194304, (ELog::Level)log_level);

	std::string center_listen = conf.Get<std::string>("center", "ip", "127.0.0.1");
	int center_port = conf.Get<int>("center", "port", 10003);
	if (CenterConnector::Instance().Connect(center_listen, center_port) != ENet::Success) {
		LOG_ERR("Failed to connect to center %s:%d", center_listen.c_str(), center_port);
		return false;
	}

	int version = conf.Get<int>("login", "version", 1);
	std::string valid_servers = conf.Get<std::string>("login", "valid_servers", "1");
	bool enable_simple = conf.Get<bool>("login", "enable_simple", false);
	LoginService::Instance().SetVerifyParam(version, valid_servers, enable_simple);

	std::string listen_ip = conf.Get<std::string>("login", "ip", "127.0.0.1");
	int listen_port = conf.Get<int>("login", "port", 10004);
	if (LoginService::Instance().Listen(listen_ip, listen_port) != ENet::Success) {
		LOG_ERR("Failed to listen on %s:%d", listen_ip.c_str(), listen_port);
		return false;
	}

	LOG_INFO("Application login started ...");
	return true;
}

RUN_APP(LoginApp);